import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';

class MapLocation {
  MapLocation({
    this.latitude,
    this.longitude,
    this.name,
    this.address,
    this.formattedAddress,
    this.province,
    this.city,
    this.district,
    this.adCode,
  });

  factory MapLocation.fromBaiduLocation(BaiduLocation location) {
    final poi = location.pois?.first;
    var formattedAddress = '';
    String? name;
    String? address;

    if (poi != null) {
      name = poi.name;
      address = poi.addr;
      formattedAddress = '${poi.addr ?? ''}${poi.name ?? ''}';
    } else {
      address = location.address;

      formattedAddress = '${address ?? ''}${location.locationDetail ?? ''}';
    }

    return MapLocation(
      latitude: location.latitude,
      longitude: location.longitude,
      name: name,
      address: address,
      formattedAddress: formattedAddress,
      province: location.province,
      city: location.city,
      district: location.district,
    );
  }

  factory MapLocation.fromReverseGeoCodeSearchResult(
      BMFReverseGeoCodeSearchResult result) {
    var name = '';

    if (result.poiRegions?.isNotEmpty == true) {
      name = result.poiRegions!.first.regionName!;
    } else if (result.poiList?.isNotEmpty == true) {
      name = result.poiList!.first.name!;
    }

    final formattedAddress = '${result.address ?? ''}$name';

    return MapLocation(
      latitude: result.location?.latitude,
      longitude: result.location?.longitude,
      address: result.address,
      formattedAddress: formattedAddress,
      province: result.addressDetail?.province,
      city: result.addressDetail?.city,
      district: result.addressDetail?.district,
    );
  }

  factory MapLocation.fromPoi(BMFPoiInfo poi) {
    return MapLocation(
      latitude: poi.pt?.latitude,
      longitude: poi.pt?.longitude,
      name: poi.name,
      address: poi.address,
      formattedAddress: '${poi.address ?? ''}${poi.name ?? ''}',
      province: poi.province,
      city: poi.city,
    );
  }

  double? latitude; // 坐标纬度
  double? longitude; // 坐标经度
  String? name; // 仅[BMFPoiInfo]包含此字段
  String? address; // 根据经纬度从地图API获取的地址信息，由逗号间隔，如中国,浙江省,杭州市,萧山区,北干街道。
  String? formattedAddress; // 根据经纬度从地图API获取的格式化后的地址信息，如浙江省杭州市萧山区北干街道博奥路。
  String? province; // 根据经纬度从地图API获取的坐标点所在省名称。
  String? city; // 根据经纬度从地图API获取的坐标点所在城市名称。
  String? district; // 根据经纬度从地图API获取的坐标点所在区。
  String? adCode; // 根据经纬度从地图API获取的行政区编码。
}
